import { vbenConfig } from "../../vbenConfig"
import utilTool from "../../util/tool"
import { IResAndReqFieldsMap, IJson } from "../../interface/type"
import { SwResult } from "../../store/swResult"

let sModelArr: string []
let sApiArr: string[]
let defHttpArr: string[]

function handleApi(sw: SwResult, apiPramAndResMap: IResAndReqFieldsMap) {
  sModelArr = []
  sApiArr = []
  defHttpArr = []
  const paths = sw.getPaths()
  for (const key of Object.keys(paths)) {
    console.log('key--------------------------->', key)
    const item = paths[key]
    const upName = utilTool.upToDownLine(item.apiName)
    sApiArr.push(` ${upName} = '${sw.getBasePath()}${key}', // ${item.description}
    `)

    const apiResult = apiPramAndResMap[item.apiName]

    let paramType = 'any'
    if (apiResult.request && apiResult.request.length > 0) {
      paramType = 'I' + utilTool.firstUp(item.apiName) + 'Param'
      sModelArr.push(paramType)
    }

    let responType = 'any'
    if (apiResult.response && apiResult.response.length > 0) {
      responType = 'I' + utilTool.firstUp(item.apiName) + 'Respon'
      sModelArr.push(responType)
    }

    if (apiResult.responseType === 'array') {
      responType = responType + '[]'
    }

    if (item.description.indexOf('导出') > -1) {
      defHttpArr.push(`
      // ${item.description}
      export function ${item.apiName} (params: ${paramType}) {
        return defHttp.downPost<${responType}>(
          {
            url: Api.${upName},
            params
          }
        );
      }
    `)
    } else {
      defHttpArr.push(`
      // ${item.description}
      export function ${item.apiName} (params: ${paramType}) {
        return defHttp.post<${responType}>(
          {
            url: Api.${upName},
            params
          }
        );
      }
    `)
    }
    console.log('apiResult>>>. ', apiResult)
  }
}

export function apiTemp(sw: SwResult, apiPramAndResMap: IResAndReqFieldsMap, pageConfig: IJson): string {
  handleApi(sw, apiPramAndResMap)
  // const basePath = vbenConfig.baseUrl.replace(/\//g, '')
  // const fileName = utilTool.firstLower(utilTool.lineToUp(`${basePath}Model`))

  const basePath = pageConfig.filePath ? pageConfig.filePath : vbenConfig.baseUrl.replace(/\//g, '')
  const fileName = utilTool.firstLower(utilTool.lineToUp(`${basePath}Model`))

  return `import { defHttp } from '/@/utils/http/axios';
  import { ${sModelArr.join(', ')}} from './model/${fileName}';
  enum Api {
    ${sApiArr.join('')}
  }

  ${defHttpArr.join('')}
  `
}
